//
//  ClubSquareView.swift
//  77Club
//
//  Created by Apple on 2024/8/28.
//

import UIKit
import VersaPlayer
import MediaPlayer

class ClubDynamicListCell: UITableViewCell, RaeNetworkProtocol {
    
    private let backView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12.0.Scale).end()
    private let moreButton = c_make_ex(UIButton.self)
        .image("Mine_Commit_more").end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let iconShadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(12.font_semiBold).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let contentLabel = c_make_ex(UITextView.self)
        .color("#47494D").font(15.font_medium).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let browseImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_look").end()
    private let commitImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_commit").end()
    private let likeImageView = c_make_ex(UIButton.self)
        .image("Square_like").image("Square_liked", state: .selected).end()
    private let browseLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).text("999浏览").end()
    private let commitLikeLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).alignment(.right).end()
    private lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 2.0.Scale
        layout.minimumInteritemSpacing = 2.0.Scale
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 0, left: 64.0.Scale, bottom: 0, right: 15.0.Scale)
        layout.itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
        return layout
    }()
    private let playerView = VersaPlayerView()
    private var controls = VersaPlayerControls()
    private let voiceButton = c_make_ex(UIButton.self)
        .image("Dynamic_detail_aloud").image("Dynamic_detail_slience", state: .selected).end()
    private let playTimeLabel = UIIconButton(style: .leading(itemSpace: 2))
    
    private var imgTapValue = [String]()
    private var topicTapValue = [String]()
    private var postTapValue = [String]()
    private var showCount = 0
    private var isPlaying = true
    
    var circleModel: ClubGameCircleModel? {
        didSet{
            guard let md = circleModel else { return }
            
            iconImageView.loadImage(url: md.face)
            nameLabel.text = md.pet_name
            contentLabel.text = ""
            let attrString = self.createAttributedText(from: md.content)
            contentLabel.attributedText = attrString
         
            timeLabel.text = md.time
            var look = md.look
            if look == "0"{
                look = ""
            }
            browseLabel.text = look + "浏览"
            var pinglun = md.pinglun
            if pinglun == "0"{
                pinglun = ""
            }
            var zan = md.zan
            if zan == "0"{
                zan = ""
            }
            commitLikeLabel.text = pinglun + "评论 · " + zan + "点赞"
            likeImageView.isSelected = md.is_zan
            playerView.isHidden = true
            collectionView.isHidden = false
            playerView.heightConstraint?.constant = 0
            browseImageView.topConstraint?.constant = 0
            if md.video.count > 0 {
                playerView.isHidden = false
                collectionView.isHidden = true
                collectionView.heightConstraint?.constant = 0
                playerView.heightConstraint?.constant = 152.0.Scale
                browseImageView.topConstraint?.constant = 152.0.Scale
                if let url = URL.init(string: md.video) {
                    let item = VersaPlayerItem(url: url)
                    playerView.set(item: item)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        self.playerView.pause()
                        self.voiceButton.isSelected = false
                    }
                }
                self.showCount = 0
            }else if md.img.count == 1 {
                collectionView.heightConstraint?.constant = 152.0.Scale
                self.showCount = 1
            }else if md.img.count == 2 {
                collectionView.heightConstraint?.constant = 85.0.Scale
                self.showCount = 2
            }else if md.img.count > 2 {
                let w = (CGFloat.screenWidth - 110.0.Scale)/3
                if md.img.count == 3 || md.img.count == 4 || md.img.count == 5 {
                    collectionView.heightConstraint?.constant = w
                    self.showCount = 3
                }else if md.img.count == 6 || md.img.count == 7 || md.img.count == 8 {
                    collectionView.heightConstraint?.constant = w * 2 + 2
                    self.showCount = 6
                }else{
                    collectionView.heightConstraint?.constant = w * 3 + 4
                    self.showCount = 9
                }
            }else{
                collectionView.heightConstraint?.constant = 0
            }

            let size = CGSize(width: CGFloat.screenWidth - 104.0.Scale, height: .greatestFiniteMagnitude)
            let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
                // 使用 boundingRect 方法计算高度
            let boundingRect = contentLabel.attributedText.boundingRect(with: size, options: options, context: nil)
            self.contentLabel.heightConstraint?.constant = ceil(boundingRect.height)
            layout.itemSize = md.itemSize
//            imgTapValue.reverse()
//            topicTapValue.reverse()
            collectionView.collectionViewLayout = layout
            collectionView.reloadData()
        }
    }
    
    var topicModel: ClubSquareTopicDataModel?{
        didSet{
            guard let md = topicModel else { return }
            // 将模型转换为 JSON 字符串
            let jsonString = md.kj.JSONObject()
            circleModel = jsonString.kj.model(ClubGameCircleModel.self)
        }
    }

    func createAttributedText(from text: String) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: text)
        
        // 默认字体和颜色
        attributedString.addAttribute(.foregroundColor, value: "#4B4C4D".toColor, range: NSRange(location: 0, length: attributedString.length))
        attributedString.addAttribute(.font, value: 15.font_regular!, range: NSRange(location: 0, length: attributedString.length))
        
        let nsText = text as NSString
        var count = 0
        var offset = 0 // 偏移量
        var index = 0  // 用于生成唯一的 actionType 标识
        
        // 正则匹配 # 和 [图片]
        let hashtagRegex = try! NSRegularExpression(pattern: "#[^\\s]+", options: [])
        let imageTextRegex = try! NSRegularExpression(pattern: "\\[图片\\](\\S+?) ", options: [])
        
        // **1. 优先处理 #标签**
        let hashtagMatches = hashtagRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in hashtagMatches {
            let matchRange = match.range(at: 0)
            guard matchRange.location != NSNotFound else { continue }
            
            let hashtagRange = NSRange(location: matchRange.location + offset, length: matchRange.length)
            guard hashtagRange.location >= 0,
                  hashtagRange.location + hashtagRange.length <= attributedString.length else { continue }
            if var substring = attributedString.attributedSubstring(from: hashtagRange).string as String? {
                if let subjects = circleModel?.subjects {
                    if substring.hasPrefix("#") {
                        substring.removeFirst()
                    }
                    if subjects.contains(where: { $0.name == substring }) {
                        index += 1
                        self.topicTapValue.append("hashtag_\(index)")
                        attributedString.addAttribute(.foregroundColor, value: "#E57617".toColor, range: hashtagRange) // 设置颜色
                        attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "hashtag_\(index)", range: hashtagRange)
                    }
                }
            }
            if var substring = attributedString.attributedSubstring(from: hashtagRange).string as String? {
                if let subjects = topicModel?.subjects {
                    if substring.hasPrefix("#") {
                        substring.removeFirst()
                    }
                    if subjects.contains(where: { $0.name == substring }) {
                        index += 1
                        self.topicTapValue.append("hashtag_\(index)")
                        attributedString.addAttribute(.foregroundColor, value: "#E57617".toColor, range: hashtagRange) // 设置颜色
                        attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "hashtag_\(index)", range: hashtagRange)
                    }
                }
            }
        }
        
        // **2. 处理 [图片]**
        let imageTextMatches = imageTextRegex.matches(in: text, options: [], range: NSRange(location: 0, length: nsText.length))
        for match in imageTextMatches {
            let fullMatchRange = NSRange(location: match.range(at: 0).location + offset, length: match.range(at: 0).length)
            let textRange = NSRange(location: match.range(at: 1).location + offset, length: match.range(at: 1).length)
            // 替换 [图片] 为图片
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: "Square_gameTag") // 替换为图片
            attachment.bounds = CGRect(x: 0, y: -7, width: 20, height: 20)
            let imageString = NSAttributedString(attachment: attachment)
            
            attributedString.replaceCharacters(in: NSRange(location: fullMatchRange.location, length: "[图片]".count), with: imageString)
            offset += imageString.length - "[图片]".count // 更新偏移量
            // 设置图片后面的文字颜色
            let updatedTextRange = NSRange(location: textRange.location + offset + (3 * count), length: textRange.length)
            if updatedTextRange.location + updatedTextRange.length <= attributedString.length {
                index += 1
                self.imgTapValue.append("imageText_\(index)")
                attributedString.addAttribute(.foregroundColor, value: "#3D9399".toColor, range: updatedTextRange)
                attributedString.addAttribute(NSAttributedString.Key("actionType"), value: "imageText_\(index)", range: updatedTextRange)
            }
            count += 1
        }
        
        return attributedString
    }

    @objc func handleTap(_ gesture: UITapGestureRecognizer) {
        let location = gesture.location(in: contentLabel)
        
        // 获取点击位置的字符索引
        if let position = contentLabel.closestPosition(to: location) {
            let characterIndex = contentLabel.offset(from: contentLabel.beginningOfDocument, to: position)
            
            // 确保 characterIndex 不超过富文本长度
            if characterIndex < contentLabel.attributedText.length {
                
                // 获取点击位置的属性
                let attributes = contentLabel.attributedText.attributes(at: characterIndex, effectiveRange: nil)
                
                // 检查是否存在 "actionType" 属性
                if let actionType = attributes[NSAttributedString.Key("actionType")] as? String {
                    if actionType.hasPrefix("hashtag_") {
                        print("The string starts with 'hashtag_'")
                        if let index = self.topicTapValue.firstIndex(of: actionType) {
                            if let gamesId = circleModel?.subjects?[index].subject_id {
                                self.toTopicDetailVC?(gamesId)
                            }else{
                                let gamesId = topicModel?.subjects?[index].subject_id ?? ""
                                self.toTopicDetailVC?(gamesId)
                            }
                        }
                    } else {
                        // 执行对应的操作
                        if let index = self.imgTapValue.firstIndex(of: actionType) {
                            if let gamesId = circleModel?.games?[index].gid {
                                self.toGameDetailVC?(gamesId)
                            }else{
                                let gamesId = topicModel?.games?[index].gid ?? ""
                                self.toGameDetailVC?(gamesId)
                            }
                        }
                    }
                }else{
                    self.jumpToDetail?(circleModel?.id ?? "")
                    
                }
            }
        }
    }

//    var likeBlock:((_:String)->())?
    var jumpToDetail:((_:String)->())?
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    /// 点击视频
    var didSelectVideo:((_:String)->())?
    /// 跳转游戏详情
    var toGameDetailVC: ((_ gameId: String) -> Void)?
    /// 更多
    var showMoreView: ((_ model: ClubGameCircleModel) -> Void)?
    var showTopicMoreView: ((_ model: ClubSquareTopicDataModel) -> Void)?
    /// 用户主页
    var otherUserInfoVC: ((_ uid: String) -> Void)?
    /// 话题主页
    var toTopicDetailVC: ((_ topicId: String) -> Void)?
    
    
    var model: ClubWuKongDataModel?{
        didSet{
            guard let md = model?.data else { return }
            circleModel = md
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            backView.subviews{
                moreButton
                iconImageView.subviews{
                    iconShadowView
                }
                nameLabel
                timeLabel
                contentLabel
                collectionView
                playerView
                browseImageView
                commitImageView
                likeImageView
                browseLabel
                commitLikeLabel
            }
        }
        
        backView.leading(12.0.Scale).trailing(12.0.Scale).top(12.0.Scale).bottom(0)
        moreButton.trailing(12.0.Scale).top(16.0.Scale).size(32.0.Scale)
        iconImageView.leading(12.0.Scale).top(16.0.Scale).size(40.0.Scale)
        iconShadowView.fillContainer()
        nameLabel.leading(64.0.Scale).top(20.0.Scale).trailing(65.0.Scale)
        timeLabel.leading(64.0.Scale).top(40.0.Scale).trailing(65.0.Scale)
        contentLabel.leading(64.0.Scale).top(64.0.Scale).trailing(16.0.Scale).height(36.0.Scale)
        collectionView.leading(0).trailing(0).height(0)
        collectionView.Top == contentLabel.Bottom + 8.0.Scale
        playerView.leading(64.0.Scale).trailing(15.0.Scale).height(0)
        playerView.Top == contentLabel.Bottom + 8.0.Scale
        browseImageView.leading(52.0.Scale).size(44.0.Scale)
        browseImageView.Top == collectionView.Bottom
        likeImageView.trailing(4.0.Scale).size(44.0.Scale)
        likeImageView.CenterY == browseImageView.CenterY
        commitImageView.size(44.0.Scale)
        commitImageView.CenterY == likeImageView.CenterY
        commitImageView.Trailing == likeImageView.Leading
        browseLabel.leading(64.0.Scale).bottom(15.0.Scale)
        browseLabel.Top == browseImageView.Bottom
        commitLikeLabel.trailing(16.0.Scale)
        commitLikeLabel.CenterY == browseLabel.CenterY
        
        playerView.use(controls: controls)
        playerView.layer.cornerRadius = 8.0.Scale
        playerView.layer.masksToBounds = true
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGameCircleCell.self, forCellWithReuseIdentifier: ClubGameCircleCell.description())
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isScrollEnabled = false
                
        let tapG = UITapGestureRecognizer.init(target: self, action: #selector(commentButtonClick))
        commitImageView.isUserInteractionEnabled = true
        commitImageView.addGestureRecognizer(tapG)
        likeImageView.addTarget(self, action: #selector(likeButtonClick), for: .touchUpInside)
        
        contentLabel.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        contentLabel.addGestureRecognizer(tapGesture)
        
        moreButton.addTarget(self, action: #selector(clickMoreButton), for: .touchUpInside)
        
        iconImageView.isUserInteractionEnabled = true
        iconShadowView.isUserInteractionEnabled = true
        let iconTap = UITapGestureRecognizer(target: self, action: #selector(clickUserIcon))
        iconShadowView.addGestureRecognizer(iconTap)
        
        contentLabel.isEditable = false
        contentLabel.isScrollEnabled = false
        contentLabel.isUserInteractionEnabled = true
        contentLabel.backgroundColor = .clear
        contentLabel.translatesAutoresizingMaskIntoConstraints = false
        contentLabel.textContainerInset = .zero
        contentLabel.textContainer.lineFragmentPadding = 0
        
        playerView.backgroundColor = .black
        playerView.playbackDelegate = self
        playerView.controls?.behaviour.shouldHideControls = false
        controls.subviews{
            voiceButton
            playTimeLabel
        }
        voiceButton.trailing(56).size(24)
        voiceButton.isSelected = true
        voiceButton.addTarget(self, action: #selector(clickVoiceButton), for: .touchUpInside)
        playTimeLabel.trailing(12).bottom(10).height(12.0.Scale)
        voiceButton.CenterY == playTimeLabel.CenterY
                
        playTimeLabel.style { v in
            v.iconSize = CGSize(width: 12.0.Scale, height: 12.0.Scale)
            v.setImage("Dynamic_time".toImage, for: .normal)
            v.setTitleColor(.white, for: .normal)
            v.titleLabel?.font = 10.font_semiBold
            v.isUserInteractionEnabled = false
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(stopAudioPlayer), name: .stopDynamicAudioPlayer, object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

//MARK: action
extension ClubDynamicListCell: VersaPlayerPlaybackDelegate {
    
    func playVideo() {
        if let video = circleModel?.video, video.count > 0 {
            playerView.play()
            playerView.player.volume = voiceButton.isSelected ? 0 : 1
        }
    }
        
    func pauseVideo() {
        if let video = circleModel?.video, video.count > 0 {
            playerView.pause()
        }
    }
    
    @objc private func stopAudioPlayer(){
        pauseVideo()
    }
    
    @objc private func clickUserIcon(){
        otherUserInfoVC?(circleModel?.uid_des ?? "")
    }
    
    @objc private func clickMoreButton(){
        
        if let md = circleModel {
            showMoreView?(md)
        }
        if let md = topicModel {
            showTopicMoreView?(md)
        }
        
    }

    @objc private func commentButtonClick() {
        jumpToDetail?(circleModel?.id ?? "")
    }
    
    @objc private func likeButtonClick(){

        guard let md = circleModel else { return }
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            ToastUtil.show()
            Task {
                let models = await network.request(.dynamicLike(type: "0", dynamicID: md.id),isShowError: false)
                ToastUtil.dismiss()
                if models.isSuccess {
                    likeImageView.isSelected = !likeImageView.isSelected
                    let strArray = commitLikeLabel.text!.components(separatedBy: " · ")
                    var zanString = strArray.last ?? ""
                    if zanString == "点赞" {
                        zanString = "1点赞"
                    }else{
                        if likeImageView.isSelected {
                            zanString = ClubGlobalTool.shared.calculateNumberInString(text: zanString)
                        }else{
                            zanString = ClubGlobalTool.shared.subtractionNumberInString(text: zanString)
                            if zanString == "0点赞"{
                                zanString = "点赞"
                            }
                        }
                    }
                    var pinglun = md.pinglun
                    if pinglun == "0"{
                        pinglun = ""
                    }
                    commitLikeLabel.text = pinglun + "评论 · " + zanString
                }
            }
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    @objc private func clickVoiceButton(){
        self.voiceButton.isSelected = !self.voiceButton.isSelected
        if self.voiceButton.isSelected {
            playerView.player.volume = 0
        }else{
            playerView.player.volume = 1
        }
    }
    
    func timeDidChange(player: VersaPlayer, to time: CMTime) {
        
//        let seconds = CMTimeGetSeconds(time)
//        let endTime = CMTimeGetSeconds(player.endTime())
        
        let currentT = CMTimeGetSeconds(time)
        let currentTStr = Int(currentT).toPlayTimeStr()
        playTimeLabel.setTitle(currentTStr, for: .normal)
        
//        if Int(seconds) == Int(endTime) {
//            player.pause()
//            let time:CMTime = CMTimeMakeWithSeconds(0.1, preferredTimescale: 1 * Int32(NSEC_PER_SEC))
//            player.seek(to: time, toleranceBefore: CMTime.zero, toleranceAfter:CMTime.zero)
//            player.play()
//        }
        
    }
}

extension ClubDynamicListCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.showCount
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let pageCell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubGameCircleCell.description(), for: indexPath) as? ClubGameCircleCell else { return UICollectionViewCell() }
        pageCell.model = circleModel
        if circleModel?.img.count ?? 0 > 0{
            pageCell.imageView.loadImage(url: circleModel?.img[indexPath.row])
            pageCell.layoutIfNeeded()
            let count = circleModel?.img.count ?? 0
            pageCell.isHiddenMore = true
            if self.showCount == 1 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 8.0.Scale)
            }else if self.showCount == 2 {
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
                }else {
                    pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8.0.Scale)
                }
            }else if self.showCount == 3{
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
                }else if indexPath.row == 2{
                    pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8.0.Scale)
                }else {
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
                }
                if count - self.showCount > 0 && indexPath.row == 2 {
                    pageCell.isHiddenMore = false
                    pageCell.moreLabel.setTitle("+\(count - self.showCount)", for: .normal)
                }else{
                    pageCell.isHiddenMore = true
                }
            }else if self.showCount == 6{
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
                }else if indexPath.row == 2{
                    pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
                }else if indexPath.row == 3 {
                    pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
                }else if indexPath.row == 5 {
                    pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
                }else{
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
                }
                if count - self.showCount > 0 && indexPath.row == 5 {
                    pageCell.isHiddenMore = false
                    pageCell.moreLabel.setTitle("+\(count - self.showCount)", for: .normal)
                }else{
                    pageCell.isHiddenMore = true
                }
            }else {
                if indexPath.row == 0 {
                    pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
                }else if indexPath.row == 2{
                    pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
                }else if indexPath.row == 6 {
                    pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
                }else if indexPath.row == 8 {
                    pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
                }else{
                    pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
                }
            }
        }
        
        return pageCell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if circleModel?.video.count ?? 0 > 0 {
            didSelectVideo?((circleModel?.video)!)
        }else{
            didSelectImage?(indexPath.row,circleModel?.img ?? [])
        }
    }
    
//    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//        
//        guard let size = circleModel?.itemSize else { return .zero }
//        
//        print("================\(size)")
//        
//        return size
//    }
}


//MARK: =============动态 img/video itemcell
class ClubGameCircleCell: UICollectionViewCell {
    
    var imageView:UIImageView!
    var playImage:UIImageView!
    let delButton = c_make_ex(UIButton.self)
        .image("Square_del").end()
    private let shadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    let moreLabel = UIIconButton(style: .leading(itemSpace: 0))
    
    var isHiddenMore = false {
        didSet{
            self.moreLabel.isHidden = isHiddenMore
            if isHiddenMore {
                shadowView.backgroundColor = .black.alpha(0.1)
            }else{
                shadowView.backgroundColor = .black.alpha(0.5)
            }
        }
    }
    
    var model: ClubGameCircleModel?{
        didSet {
            guard let md = model else { return }
            if md.video.count > 0 {
                playImage.isHidden = false
                if md.img.count > 0 {
                    self.imageView.loadImage(url: md.img.first)
                }else{
                    self.imageView.image = nil
                }
            }else {
                playImage.isHidden = true
            }
        }
    }
    
    var forumModel: ClubGameCommunityListModel?{
        didSet {
            guard let md = forumModel else { return }
            if md.video.count > 0 {
                playImage.isHidden = false
                if md.image.count > 0 {
                    self.imageView.loadImage(url: md.image.first)
                }else{
                    self.imageView.image = nil
                }
            }else {
                playImage.isHidden = true
            }
        }
    }
    
    var commitModel: ClubGameDetailCommentListModel?{
        didSet {
            guard let md = commitModel else { return }
            if md.video.count > 0 {
                playImage.isHidden = false
                if md.images.count > 0 {
                    self.imageView.loadImage(url: md.images.first)
                }else{
                    self.imageView.image = nil
                }
            }else {
                playImage.isHidden = true
            }
        }
    }
    
    var index = 0
    var delBlock: ((_ delIndex: Int) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initUI()
        
        initFrame()
        
    }
    
    private func initUI() -> Void {

        // 可选：设置 contentView 的背景颜色以便于对比
        self.contentView.backgroundColor = UIColor.clear
        
        imageView = UIImageView.init()
        imageView.backgroundColor = UIColor.clear
        imageView.layer.masksToBounds = true
        imageView.contentMode = UIView.ContentMode.scaleAspectFill
        contentView.addSubview(imageView)
        
        imageView.addSubview(shadowView)
        
        playImage = UIImageView()
        playImage.image = UIImage(named: "Square_play")
        imageView.addSubview(playImage)
        playImage.isHidden = true
        
        delButton.isHidden = true
        delButton.addTarget(self, action: #selector(clickDelButton), for: .touchUpInside)
        contentView.addSubview(delButton)
        
        moreLabel.style { v in
            v.iconSize = CGSize(width: 22, height: 21)
            v.setImage("Dynamic_morePic".toImage, for: .normal)
            v.setTitleColor(.white, for: .normal)
            v.titleLabel?.font = 13.font_semiBold
            v.isHidden = true
            v.isUserInteractionEnabled = false
        }
        contentView.addSubview(moreLabel)
    }
    
    private func initFrame() -> Void {
        
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        shadowView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        playImage.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        delButton.snp.makeConstraints { make in
            make.top.trailing.equalToSuperview()
            make.width.height.equalTo(32)
        }
        
        moreLabel.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
        }
    }
    
    @objc private func clickDelButton(){
        delBlock?(index)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
